
<template>
    <main :style="{ backgroundImage: `url(${url})` }">
        <template v-if="current">
            <div class="header" >
                <div class="left">
                    <img alt="" class="back" :src="url1" @click="back" />
                    <span>{{ name }}</span>
                </div>
                <div class="middle">
                    <span :style="{ color: titleColor() }">单词跟读</span>
                </div>
                <div class="right">
                    <Progress class="progress" :max="list.length" :value="currentIndex + 1" :progressColor="progressColor()"></Progress>
                    <!-- <div class="progress-wrap">
                        <progress :class="[`progress-${path}`]" :max="list.length" :value="currentIndex + 1"></progress>
                        <span>{{ `${currentIndex + 1}/${list.length}` }}</span>
                    </div> -->
                </div>
            </div>
            <div class="article">
                <div v-aspectRatio class="card-wrap" :style="{ backgroundColor: cardWrapColor() }">
                    <div class="text-wrap">
                        <span class="text-en" v-html="current.content"></span>
                        <span class="text-ph" v-html="current.phonetic"></span>
                        <span class="text-cn" v-html="current.translation"></span>
                    </div>
                    <div class="cell-icon" @click="click">
                        <img :src="urlCPlay" alt="">
                    </div>
                </div>
            </div>
            <div class="footer" @click.prevent="functionEvent">
                <div class="footer-wrap">
                    <div @click.prevent="prev"
                        class="footer-btn-wrap footer-btn-left-wrap">
                        <div class="footer-btn">
                            <template v-if="currentIndex == 0">
                                <img alt=""
                                :src="urlPreGray"
                                style="width: 100%; height: 100%" />
                            </template>
                            <template v-else>
                                <img alt=""
                                :src="urlPre"
                                style="width: 100%; height: 100%" />
                            </template>
                        </div>
                        <span class="footer-btn-title">上一个</span>
                    </div>
                    <div 
                        v-show="!recordingOpen"
                        :style="{ color: '#333' }" 
                        class="footer-btn-wrap footer-btn-middle-wrap"
                        @click.prevent="read">
                        <div class="footer-btn footer-btn-middle reading">
                            <img alt="" :src="urlRecord" style="width: 100%; height: 100%" />
                        </div>
                        <span class="footer-btn-title">{{ current.read ? "再读一次" : "跟读测评" }}</span>
                    </div>
                    <div @click.prevent="next"
                        class="footer-btn-wrap  footer-btn-right-wrap">
                        <div class="footer-btn">
                            <img alt="" :src="urlNext" style="width: 100%; height: 100%" />
                        </div>
                        <span class="footer-btn-title">{{ currentIndex >= list.length - 1 ? '提交': '下一个' }}</span>
                    </div>
                </div>
            </div>
        </template>
    </main>
    <Dialog :open="recordingOpen">
        <img alt="" class="recording" src="../public/assets/expression/ty_tb_3_pt@2x.png" />
        <div class="animation footer-btn-wrap footer-btn-record-middle-wrap"
            :style="{ color: 'white' }" 
            @click.prevent="read">
            <div class="footer-btn footer-btn-middle reading">
                <img alt="" :src="urlRecord" style="width: 100%; height: 100%" />
            </div>
            <span class="footer-btn-title">点击停止</span>
        </div>
    </Dialog>
    <Dialog :open="evaluatonFinished">
        <div class="dialog-wrap-evaluation">
            <div class="pop-card-wrap">
                <div class="score-wrap">
                    <div class="score" :style="{ backgroundImage: `url(${url3})` }">
                        <span>{{ current.total }}</span>
                    </div>
                    <div class="label"> {{ current.total ? `恭喜你获得${current.total}分`: '再接再厉！' }} </div>
                    <div class="star-wrap">
                        <template v-for="i of 5">
                            <template v-if="i <= current.originTotal">
                                <img class="star star1" src="../public/assets/vocabulary/dc_tb_10_pt@2x.png">
                            </template>
                            <template v-else>
                                <img class="star star2" src="../public/assets/vocabulary/dc_tb_11_pt@2x.png">
                            </template>
                        </template>
                    </div>
                    <div class="word" v-html="current.content"></div>
                </div>
                <button class="close-button" @click="evaluatonFinished = false"></button>
            </div>
        </div>
    </Dialog>
    <Dialog :open="allFinished">
        <div class="dialog-wrap-finished">
            <div class="content">
                <img alt="" src="../public/assets/vocabulary/ty_tb_14_pt@2x.png" />
                <span>你真棒，完成了全部的单词学习。</span>
                <div class="control">
                    <button @click="onClickBack" class="button btn-back"
                    :style="{ background: buttonBackColor() }"
                    >返回单元</button>
                    <button @click="onClickAgin" class="button btn-agin"
                    :style="{ background: buttonAginColor() }"
                    >再来一遍</button>
                </div>
            </div>
        </div>
    </Dialog>
    <Dialog :open="audioAuth">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioAuth = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-auth" src="../public/assets/expression/diandu_tb_16_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    请打开麦克风访问权限
                </div>
            </div>                
        </div>
    </Dialog>
    <Dialog :open="audioNoDevice">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioNoDevice = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-device" src="../public/assets/expression/diandu_tb_17_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    很抱歉，监测到您的设备没有麦克风
                </div>
            </div>                
        </div>
    </Dialog>
    <Dialog :open="audioNoNet">
        <div class="dialog-wrap-auth">
            <div class="content">
                <div class="button-wrap">
                    <button class="close-button"
                        :style="{ backgroundImage: `url(${url2})` }"
                        @click="audioNoNet = false"></button>
                </div>
                <div class="icon-wrap">
                    <img class="icon icon-net" src="../public/assets/expression/diandu_tb_15_pt@2x.png" alt="">
                </div>
                <div class="label-wrap">
                    网络不佳，请稍等片刻
                </div>
            </div>                
        </div>
    </Dialog>
</template>

<script setup>
import { onMounted, ref, reactive, toRefs, watch, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import AudioWebsocket from './../utils/audio.js'
import Dialog from "../component/dialog/index.vue";
import { getVocabularyDetailApi } from "../api/expression.js"
import '../css/evaluation.css'
import Progress from "../component/progress/index.vue";

const router = useRouter();
const route = useRoute();
const { id, name } = route.query;

const path = window.gradeId > 61 ? 'middle' : 'primary';

const url =  new URL(`../public/assets/vocabulary/${path}/d_bg.png`, import.meta.url).href;
const url1 = new URL(`../public/assets/book/${path}/back.png`, import.meta.url).href;
const url2 = new URL(`../public/assets/expression/${path}/poprightclose.png`, import.meta.url).href;
const url3 = new URL(`../public/assets/vocabulary/${path}/scorebg.png`, import.meta.url).href;
const urlNext = new URL(`../public/assets/expression/${path}/next.png`, import.meta.url).href;
const urlNextGray = new URL(`../public/assets/expression/${path}/next_gray.png`, import.meta.url).href;
const urlRecord = new URL(`../public/assets/expression/${path}/record.png`, import.meta.url).href;
const urlPre = new URL(`../public/assets/expression/${path}/pre.png`, import.meta.url).href;
const urlPreGray = new URL(`../public/assets/expression/${path}/pre_gray.png`, import.meta.url).href;
const urlCPlay = new URL(`../public/assets/expression/${path}/c_play.png`, import.meta.url).href;

const state = reactive({
    list: [],
    current: null,
    currentIndex: 0
});

// 1 数组随机  2 科大讯飞type
const { list, current, currentIndex } = toRefs(state);

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// state.list = shuffleArray(detail[id]);

// state.current = state.list[0];

const readBtnTitle = ref("跟读测评");
const recordingOpen = ref();
const evaluatonFinished = ref(false)
const allFinished = ref(false);
const audioAuth = ref(false);
const audioNoDevice = ref(false);
const audioNoNet = ref(false);

const audio = new Audio();

const getVocabularyDetail = async (id) => {
    // state.list = shuffleArray(detail[id]);
    // state.current = state.list[0];
    // audioPlay();

    try {
        const res = await getVocabularyDetailApi(id);
        // console.log('res', res);
        if (res.data && res.data.length) {
            state.list = shuffleArray(res.data);
            state.current = state.list[0];
            audioPlay();
        }

    } catch (error) {
        // console.log(error);
    }
}

const audioPlay = (url) => {
    if (!audio.paused) {
        audio.pause();
    }
    audio.src = url || state.list[state.currentIndex].audio_url;
    audio.play();
}

const audioStop = () => {
    audio.pause();
}

onMounted(() => {
    getVocabularyDetail(id);
});

onUnmounted(() => {
    audioStop();
    if (timer) {
        clearTimeout(timer);
    }
})

const back = () => {
    router.go(-1)
}

function prev() {
    if (state.currentIndex <= 0) {
        return;
    }
    state.currentIndex--;
    state.current = state.list[state.currentIndex];
    audioPlay();
}

let timer = null;
const timeout = () => {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(() => {
        read();
    }, 20 * 1000);
}

let isClickRead = false;
function read() {
    if (isClickRead) return
    isClickRead = true;
    onRead();
    // setTimeout(() => {
    //     isClickRead = false
    // }, 1000)
}

const onRead = () => {
    if (recordingOpen.value) {
        stopRead();
    } else {
        audioStop();
        AudioWebsocket.hasAudioinput().then(() => {
            let content = state.current.content.replace(/<[^>]*>/g, '').replace(/[^a-zA-Z0-9\.\-\' ]/g, "");
            console.log('content',content);
            // console.log('麦克风权限已获取');
            AudioWebsocket.startRecording(content, 'word', (result) => {
                // console.log('result', result);
                state.current.total = parseInt(result.total * 20);
                state.current.originTotal = parseInt(result.total);
                state.current.read = true;

                evaluatonFinished.value = true;
            }).then(() => {
                recordingOpen.value = true;
                readBtnTitle.value = "点击停止";
                timeout();
                isClickRead = false;
            }).catch(errorCode => {
                if (errorCode == 40001) {
                    // 无法获取麦克风权限
                    audioAuth.value = true;
                } else if ( errorCode == 40002 ) {
                    // 连接websocket失败
                    audioNoNet.value = true;
                    stopRead();
                }
                isClickRead = false;
            });
        }).catch(error => {
            // 未获取麦克风设备
            audioNoDevice.value = true;
            isClickRead = false;
        });
    }
}

const stopRead = () => {
    console.log('点击停止');
    recordingOpen.value = false;
    readBtnTitle.value = "跟读测评";
    AudioWebsocket.stopRecording();
    if (timer) {
        clearTimeout(timer);
    }
    isClickRead = false;
}

// function read() {
//     if (recordingOpen.value) {
//         recordingOpen.value = false;
//         readBtnTitle.value = "跟读测评";
//         AudioWebsocket.stopRecording();
//         if (timer) {
//             clearTimeout(timer);
//         }
//     } else {
//         recordingOpen.value = true;
//         readBtnTitle.value = "点击停止";
//         AudioWebsocket.startRecording(state.current.content, 'word', (result) => {
//             // console.log('result', result);
//             state.current.total = parseInt(result.total * 20);
//             state.current.originTotal = parseInt(result.total);

//             evaluatonFinished.value = true;
//         });
//         timeout();
//     }
// }

function next() {
    if (state.currentIndex >= state.list.length - 1) {
        audioStop();
        allFinished.value = true;
        return;
    }
    state.currentIndex++;
    state.current = state.list[state.currentIndex];
    audioPlay();
}
function click() {
    audioPlay();
}

const onClickBack = () => {
    allFinished.value = false;
    router.go(-1);
}

const onClickAgin = () => {
    allFinished.value = false;
    // state.list = shuffleArray(state.list);
    state.current = state.list[0];
    state.currentIndex = 0;
}

const titleColor = () => {
    if (path == 'middle') {
        return '#222'
    } else {
        return '#854B22'
    }
}

const cardWrapColor = () => {
    if (path == 'middle') {
        return '#fff'
    } else {
        return '#FFFAF1'
    }
}

const buttonBackColor = () => {
    if (path == 'middle') {
        return '#FFA53E'
    } else {
        return 'linear-gradient(to bottom, #FFC55E, #ED9900)'
    }
}

const buttonAginColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return 'linear-gradient(to bottom, #85D389, #61BD66)'
    }
}

const progressColor = () => {
    if (path == 'middle') {
        return '#1E4BA6'
    } else {
        return '#FFB530'
    }
}

</script>


<style scoped>

.card-wrap {
    background-color: #FFFAF1;
    border-radius: 1rem;
    width: 70%;
    /* height: 100%; */
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* justify-content: space-around; */
    position: relative;
    /* margin: 3.5rem 0 3.5rem 0; */
}

.text-wrap {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.text-en {
    color: #222222;
    font-weight: bold;
    font-size: 2.2rem;
    /* margin-top: 10rem; */
    font-family: 'text-en';
}

.text-ph {
    color: #666666;
    font-size: 1.8rem;
    line-height: 1.5rem;
    margin-top: 1rem;
    font-family: 'text-phonetic';
}

.text-cn {
    color: #222222;
    font-size: 2rem;
    margin-top: 4rem;
    padding: 0 10%;
}

.cell-icon {
    cursor: pointer;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    position: absolute;
    top: 6%;
    right: 4%;
}

.cell-icon img {
    width: 2rem;
}

</style>